package com.jy.rhin.application.cda;

import com.google.common.collect.Sets;
import com.jy.api.healthreord.HealthRecordAPI;
import com.jy.api.healthreord.dto.jk.JkHuizhenJlDto;
import com.jy.common.StringUtil;
import com.jy.framework.base.entity.Result;
import com.jy.framework.base.utils.Converter;
import com.jy.rhin.domain.cda.CDACreator;
import com.jy.rhin.infra.cda.CDAException;
import com.jy.rhin.model.ClinicalDocumentData;
import com.jy.rhin.model.HuiZhenJL;
import com.jy.rhin.model.body.huizhen.HuiZhenYJ;
import com.jy.rhin.model.body.huizhen.HuiZhenYY;
import com.jy.rhin.model.header.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class HuiZhenJLApplication {
    private static final String FTL_PATH = "/19huizhenjilu.ftl";
    @Resource
    private CDACreator cdaCreator;
    @Autowired
    private HealthRecordAPI healthRecordAPI;
//    @Resource
//    private DataMigrationAPI dataMigrationAPI;
//    @Resource
//    private HospitalAPI hospitalAPI;

    /**
     * @param huizhendh 会诊单号
     * @param yewujgdm  业务机构代码(医院)
     * @return
     */
    public String create(String huizhendh, String yewujgdm) {
        Result<List<JkHuizhenJlDto>> result = healthRecordAPI.getByHuizhenDhs(yewujgdm, Sets.newHashSet(huizhendh));
        if (!result.isSuccess() || CollectionUtils.isEmpty(result.getData())) {
            throw new CDAException("会诊数据不存在：" + huizhendh + ":" + yewujgdm, null);
        }
        if (CollectionUtils.size(result.getData()) > 1) {
            log.warn("会诊数据发现多条：{}，{}", huizhendh, yewujgdm);
        }

        JkHuizhenJlDto huizhenDTO = result.getData().get(0);
        HuiZhenJL huizhen = new HuiZhenJL();
        setClinicalDocumentData(huizhen, huizhenDTO);
        huizhen.setId(huizhenDTO.getHuizhendh());

        LegalAuthenticator legalAuth = new LegalAuthenticator();
        legalAuth.setTime(toD8(huizhenDTO.getChuangjiansj()));
        legalAuth.setName(huizhenDTO.getZerenysxm());
        huizhen.setLegalAuthenticator(legalAuth);

        HuiZhenYY huiZhenYY = new HuiZhenYY();
        huiZhenYY.setHUIZHENYY(StringUtil.isNullOrEmpty(huizhenDTO.getHuizhenyy()) ? "-" : huizhenDTO.getHuizhenyy());
        huizhen.setHuiZhenYY(huiZhenYY);

        HuiZhenYJ huiZhenYJ = new HuiZhenYJ();
        huiZhenYJ.setHUIZHENRQ(toD8(huizhenDTO.getHuizhensj()));
        huiZhenYJ.setHUIZHENYJ(huizhenDTO.getHuizhenyj());
        huiZhenYJ.setHUIZHENZJXM(huizhenDTO.getHuizhenzjxm());
        huiZhenYJ.setYEWUJGDM(huizhenDTO.getHuizhenzjjgoutid());
        huiZhenYJ.setHUIZHENKSMC(huizhenDTO.getYewuksmc());
        huiZhenYJ.setYEWUJGMC(huizhenDTO.getHuizhenzjjgmc());
        huizhen.setHuiZhenYJ(huiZhenYJ);

        return cdaCreator.create(huizhen, FTL_PATH);
    }

//    public String create(HuiZhenDTO huiZhenDTO) {
//        HuiZhenJL huizhen = new HuiZhenJL();
//
//        HospitalDTO hospital = dataMigrationAPI.getByHospitalId(huiZhenDTO.getShenQingHospitalId()).getData();
//        HospitalDTO hospital = hospitalAPI.info(huiZhenDTO.getShenQingHospitalId()).getData();
//        if (Objects.isNull(hospital)) {
//            throw new CDAException("机构数据不存在", null);
//        }
//        tranData(huiZhenDTO, hospital);
//
//        setClinicalDocumentData(huizhen, huiZhenDTO, hospital);
//        huizhen.setId(String.valueOf(huiZhenDTO.getId()));
//
//        LegalAuthenticator legalAuth = new LegalAuthenticator();
//        legalAuth.setTime(toD8(huiZhenDTO.getChuangJianSJ()));
//        legalAuth.setSignatureCode("signatureCode");
//        legalAuth.setId(HuiZhenDTO.getZERENYSDM());
//        legalAuth.setName(huiZhenDTO.getShenQingYSXM());
//        huizhen.setLegalAuthenticator(legalAuth);
//
//        HuiZhenYY huiZhenYY = new HuiZhenYY();
//        huiZhenYY.setHUIZHENYY(StringUtil.isNullOrEmpty(huiZhenDTO.getHuiZhenMD()) ? "-" : huiZhenDTO.getHuiZhenMD());
//        huizhen.setHuiZhenYY(huiZhenYY);
//
//        if (!CollectionUtils.isEmpty(huiZhenDTO.getHuiZhenYJList())) {
//            HuiZhenYJ huiZhenYJ = new HuiZhenYJ();
//            HuiZhenYJDTO huiZhenYJDTO = huiZhenDTO.getHuiZhenYJList().get(0);
//            huiZhenYJ.setHUIZHENRQ(toD8(huiZhenYJDTO.getJieZhiSJ()));
//            huiZhenYJ.setHUIZHENYJ(huiZhenYJDTO.getHuiZhenYJ());
//            huiZhenYJ.setHUIZHENZJXM(huiZhenYJDTO.getHuiZhenYSXM());
//            if (!huiZhenYJDTO.getHuiZhenYSHospitalId().equals(huiZhenDTO.getShenQingHospitalId())) {
//                HospitalDTO huiZhenHospital = hospitalAPI.info(huiZhenYJDTO.getHuiZhenYSHospitalId()).getData();
////                HospitalDTO huiZhenHospital = dataMigrationAPI.getByHospitalId(huiZhenYJDTO.getHuiZhenYSHospitalId()).getData();
//                huiZhenYJ.setYEWUJGDM(huiZhenHospital.getOutId());
//            } else {
//                huiZhenYJ.setYEWUJGDM(hospital.getOutId());
//            }
//            huiZhenYJ.setHUIZHENKSMC(huiZhenDTO.getShenQingYSKSMC());
//            huiZhenYJ.setYEWUJGMC(huiZhenDTO.getShenQingHospitalName());
//
//            huizhen.setHuiZhenYJ(huiZhenYJ);
//        }
//
//        return cdaCreator.create(huizhen, FTL_PATH);
//    }


//    private void tranData(HuiZhenDTO huiZhenDTO, HospitalDTO hospital) {
//        huiZhenDTO.setGERENDABS(toLength17(HuiZhenDTO.getGERENDABS()));
//        HuiZhenDTO.setYEWUJGDM(to10YiLiaoJGDM(HuiZhenDTO.getYEWUJGDM()));
//
//        hospital.setHospitalId(to10YiLiaoJGDM(hospital.getHospitalId()));
//    }

    private void setClinicalDocumentData(ClinicalDocumentData clinicalDocumentData, JkHuizhenJlDto huizhenDTO) {
        clinicalDocumentData.setEffectiveTime(toDT15(huizhenDTO.getChuangjiansj()));
        clinicalDocumentData.setPatientRole(createPatientRole(huizhenDTO));
        clinicalDocumentData.setAuthor(createAuthor(huizhenDTO));
        clinicalDocumentData.setCustodian(createCustodian(huizhenDTO));
        clinicalDocumentData.setSetId(huizhenDTO.getId());
        clinicalDocumentData.setVersionNumber("1");
    }

//    private void setClinicalDocumentData(ClinicalDocumentData clinicalDocumentData, HuiZhenDTO huiZhenDTO, HospitalDTO hospital) {
//        clinicalDocumentData.setEffectiveTime(toDT15(huiZhenDTO.getChuangJianSJ()));
//        clinicalDocumentData.setPatientRole(createPatientRole(huiZhenDTO));
//        clinicalDocumentData.setAuthor(createAuthor(huiZhenDTO, hospital));
//        clinicalDocumentData.setCustodian(createCustodian(hospital));
//        clinicalDocumentData.setSetId(String.valueOf(huiZhenDTO.getId()));
//        clinicalDocumentData.setVersionNumber("1");
//    }

    Custodian createCustodian(JkHuizhenJlDto info) {
        Custodian custodian = new Custodian();
        custodian.setId(info.getYewujgoutid());// 特殊
        custodian.setName(info.getYewujgmc());
        custodian.setAddr(info.getYewujgdz());
        return custodian;
    }

//    Custodian createCustodian(HospitalDTO hospital) {
//        Custodian custodian = new Custodian();
//        custodian.setId(hospital.getOutId());
//        custodian.setName(hospital.getName());
//        custodian.setAddr(hospital.getAddress());
//        return custodian;
//    }

    Author createAuthor(JkHuizhenJlDto info) {
        Author author = new Author();
        author.setId(info.getZerenysdm());
        author.setTime(toDT15(info.getChuangjiansj()));
        author.setName(info.getZerenysxm());
        author.setOrganizationId(info.getYewujgoutid());// 特殊
        author.setOrganizationName(info.getYewujgmc());
        author.setOrganizationAddr(info.getYewujgdz());
        return author;
    }

//    Author createAuthor(HuiZhenDTO info, HospitalDTO hospital) {
//        Author author = new Author();
//        author.setId(info.getShenQingYSDM());
//        author.setTime(toDT15(info.getChuangJianSJ()));
//        author.setName(info.getShenQingYSXM());
//        author.setOrganizationId(hospital.getOutId());
//        author.setOrganizationName(hospital.getName());
//        author.setOrganizationAddr(hospital.getAddress());
//        return author;
//    }

    PatientRole createPatientRole(JkHuizhenJlDto info) {
        PatientRole patientRole = new PatientRole();
        // 固定长度17位
        patientRole.setId(toLength17(info.getGerendabs()));
        patientRole.setPatient(createPatient(info));
        return patientRole;
    }

//    PatientRole createPatientRole(HuiZhenDTO info) {
//        PatientRole patientRole = new PatientRole();
//        // 固定长度17位
//        patientRole.setId(toLength17(String.valueOf(info.getBingRenId())));
//        patientRole.setPatient(createPatient(info));
//        return patientRole;
//    }

    Patient createPatient(JkHuizhenJlDto info) {
        Patient patient = new Patient();
        patient.setName(info.getXingming());
        patient.setId(info.getShenfenzh());
        return patient;
    }

//    Patient createPatient(HuiZhenDTO info) {
//        Patient patient = new Patient();
//        patient.setName(info.getBingRenXM());
//        patient.setId(info.getZhengJianHM());
//        return patient;
//    }

    private String toD8(Date date) {
        if (date == null) return null;
        return Converter.toString(date, "yyyyMMdd");
    }

    private String toDT15(Date date) {
        if (date == null) return null;
        return Converter.toString(date, "yyyyMMddHHmmss");
    }

    private String toLength17(String gerendabs) {
        if (gerendabs.length() < 17) {
            return StringUtil.padRight(gerendabs, 17, '0');
        }
        return gerendabs.substring(0, 17);
    }

    private String to10YiLiaoJGDM(String yiliaojgdm) {
        return yiliaojgdm.substring(0, 10);
    }
}
